<?php
class country extends Model{
	public static function getTableName(){
		return 'country';
	}

    public function getCountryList()
    {
        $sql = 'SELECT * FROM gaoip_country order by system_label';
        $rst = Model::selectBySql($sql);

		// append by vanni for bug:498
		$order_array = array('Hong Kong','China','Macau');
		foreach($order_array as $order=>$item){
			$sub_sql[] = "SELECT $order AS order_id,'$item' as system_label";
		}
		$order_sql = 'SELECT g.* FROM gaoip_country AS g INNER JOIN (';
		$order_sql.= implode(' UNION ALL ',$sub_sql);
		$order_sql.= ") AS o ON g.system_label = o.system_label WHERE g.system_label IN('";
		$order_sql.= implode("','",$order_array);
		$order_sql.= "') ORDER BY o.order_id DESC";
		$order_record = Model::selectBySql($order_sql);

		foreach($order_record as $record){
			$index = array_search($record,$rst);
			$temp  = $rst[$index];
			unset($rst[$index]);
			array_unshift($rst,$temp);
		}
		return $rst;
    }

	/**
	 * @param string $srcList input Ex: CN,hk,NOTEXISTS,JP
	 * @param array & $desList output(is checked ok) Ex: array('CN','HK','JP')
	 * @return boolean
	 */
	public static function checkGaoCountryList($srcList,&$desList)
	{
		$values = explode(',',$srcList);
		$values = array_unique($values);
		$total  = count($values);
		$desList= array();
		
		if($total==0) return true;

		$values = "'".implode("','",$values)."'";

		$query  = "select code from gaoip_country where code in($values)";
		$result = Model::selectBySql($query);
		foreach($result as $row){
			$desList[] = $row['code'];
		}
		return ($total == count($desList));
	}

	/**
	 * get country name
	 *
	 * @param int $country_id : country id
	 *
	 * @used by : action/InfoBiographyUpdateAction.class.php,
	 * @used by : action/InfoBiographyUpdateAction.class.php
	 * @used by : action/InfoGetAction.class.php
	 */
	public static function getCountryName($country_id)
	{
		$country_id = is_null($country_id) ? '' : $country_id;
        $sql=   'SELECT * FROM country where id=\''.$country_id.'\'';
        $ret=   Model::$dbo['r']->findBySql(__class__, $sql);
        return isset($ret[0]) ? $ret[0]->system_label : '';
	}
}
?>
